<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="姓名" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入姓名" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <!-- <el-form-item label="系统" prop="systemId">
            <el-select v-model="queryParams.systemId" placeholder="请选择所属系统" clearable style="width: 200px">
               <el-option
                  v-for="system in dataSystemOptions"
                  :key="system.id"
                  :label="system.name"
                  :value="system.id"
               />
            </el-select>
         </el-form-item> -->
         <el-form-item label="状态" prop="enabled">
            <el-select v-model="queryParams.enabled" placeholder="运行状态" clearable style="width: 200px">
               <el-option label="全部" :value="null" />
               <el-option label="启用" :value="1" />
               <el-option label="停用" :value="0" />
            </el-select>
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch">删除</el-button>
         </el-col>
         <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-if="refreshTable" v-loading="loading" :data="menuList" row-key="menuId"
         :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
         @selection-change="handleSelectionChange">
         <el-table-column type="selection" :selectable="selectable" width="55" />
         <el-table-column prop="comment" label="名称" width="150"></el-table-column>
         <el-table-column prop="name" label="表名" width="150"></el-table-column>
         <!-- <el-table-column prop="systemId" label="所属系统">
            <template #default="scope">{{ getSystemNameById(scope.row.systemId) }}</template>
         </el-table-column> -->
         <el-table-column label="状态" align="center" prop="createTime">
            <template #default="scope">{{ scope.row.enabled ? '启用' : '停用' }}</template>
         </el-table-column>
         <el-table-column label="操作" fixed="right" align="center" width="280" class-name="small-padding fixed-width">
            <template #default="scope">
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
               <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete"
                  @click="handleDelete(scope.row)">删除</el-button>
                  <el-button v-if="scope.row.enabled" link type="danger" icon="SwitchButton" @click="handleEnable(scope.row.id, 0)">停用</el-button>
                  <el-button v-else link type="success" icon="Check" @click="handleEnable(scope.row.id, 1)">启用</el-button>
            </template>
         </el-table-column>
      </el-table>
      <pagination
         v-show="total > 0"
         :total="total"
         v-model:page="queryParams.pageNum"
         v-model:limit="queryParams.pageSize"
         @pagination="getList"
      />
      <!-- 添加或修改 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
         <el-form ref="editRef" :model="form" :rules="rules">
            <el-row :gutter="10">
               <el-col :span="12">
                  <el-form-item label="名称" prop="comment">
                     <el-input v-model="form.comment" placeholder="请输入名称" />
                  </el-form-item>
               </el-col>
               <!-- <el-col :span="12">
                  <el-form-item label="系统" prop="systemId">
                     <el-select v-model="form.systemId" placeholder="所属系统" clearable>
                        <el-option
                           v-for="system in dataSystemOptions"
                           :key="system.id"
                           :label="system.name"
                           :value="system.id"
                        />
                     </el-select>
                  </el-form-item>
               </el-col> -->
               <el-col :span="12">
                  <el-form-item label="表名" prop="name">
                     <el-input v-model="form.name" @input="nameInput" placeholder="仅支持输入英文字母和下划线" />
                  </el-form-item>
               </el-col>
            </el-row>
            <el-row style="display: flex; align-items: center;">
               <el-upload
                  v-loading="uploading"
                  :on-change="importFile"
                  :limit="1"
                  :show-file-list="false"
                  :auto-upload="false"
                  accept=".xlsx, .xls"
                  ref="fileUpload"
               >
                  <el-button type="primary">导入字段</el-button>
               </el-upload>
               <a style="color: #409EFF; margin-left: 20px;" @click="downloadTemplate">下载模板</a>
            </el-row>
            <el-row class="edit-list header" :gutter="10">
               <el-col :span="4" style="text-align: center;">字段类型</el-col>
               <el-col :span="4" style="text-align: center;">字段</el-col>
               <el-col :span="4" style="text-align: center;">数据类型</el-col>
               <el-col :span="4" style="text-align: center;">长度</el-col>
               <el-col :span="5" style="text-align: center;">说明</el-col>
               <el-col :span="2"></el-col>
            </el-row>
            <div class="list" v-loading="uploading">
               <el-row class="edit-list content" :gutter="10" v-for="config, index in form.columns" :key="config.id ?? index">
                  <el-col :span="4">
                     <el-form-item :prop="'columns.' + index + '.category'" :rules="rules.columnCategory">
                        <el-select v-model="config.category" placeholder="请选择" clearable>
                           <el-option label="普通" :value="1" />
                           <el-option label="字典" :value="2" />
                           <el-option label="文件" :value="3" />
                        </el-select>
                     </el-form-item>
                  </el-col>
                  <el-col :span="4">
                     <el-form-item :prop="'columns.' + index + '.name'" :rules="rules.columnName">
                        <el-input v-model="config.name" placeholder="请输入字段" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="4">
                     <el-form-item :prop="'columns.' + index + '.type'" :rules="rules.columnType">
                        <el-select v-model="config.type" placeholder="请选择" clearable>
                           <el-option label="变长字符串" value="varchar" />
                           <el-option label="数字" value="int" />
                           <!-- <el-option label="文件流" value="blob" /> -->
                           <el-option label="长文本数据" value="text" />
                           <el-option label="极大文本数据" value="longtext" />
                        </el-select>
                     </el-form-item>
                  </el-col>
                  <el-col :span="4">
                     <el-form-item v-if="['text', 'longtext'].includes(config.type)">
                        <el-input-number
                           type="number"
                           :min="0"
                           controls-position="none"
                           :step="1"
                           step-strictly
                           disabled
                           placeholder="长度"
                           style="width: auto;"
                        />
                     </el-form-item>
                     <el-form-item v-else :prop="'columns.' + index + '.len'" :rules="rules.columnLength">
                        <el-input-number
                           type="number"
                           :min="0"
                           controls-position="none"
                           :step="1"
                           step-strictly
                           v-model="config.len"
                           placeholder="长度"
                           style="width: auto;"
                        />
                     </el-form-item>
                  </el-col>
                  <el-col :span="5">
                     <el-form-item>
                        <el-input v-model="config.comment" placeholder="请输入说明" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="2" style="justify-content: flex-start;">
                     <el-button
                        link
                        type="danger"
                        icon="Minus"
                        @click="toggleConfig('minus', index)"
                         style="margin-bottom: 18px;"
                     ></el-button>
                     <el-button
                        v-if="index === form.columns.length - 1"
                        link
                        type="primary"
                        icon="Plus"
                        @click="toggleConfig('add', index)"
                        style="margin-bottom: 18px;"
                     ></el-button>
                  </el-col>
               </el-row>
               <el-row class="edit-list content" :gutter="10" v-if="!form.columns?.length">
                  <el-col :span="21" style="color: gray;">暂无字段数据</el-col>
                  <el-col :span="2" style="justify-content: flex-start;">
                     <el-button link type="primary" icon="Plus" @click="toggleConfig('add', 0)"></el-button>
                  </el-col>
               </el-row>
            </div>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu">
import { ref, watch } from "vue";
import {
   objectModelGetListByPage,
   objectModelUpdate,
   objectModelAdd,
   objectModelDelete,
   objectModelEnable,
   objectModelExcelParse
} from "@/api/objectModel";
import { dataSystemGetList } from "@/api/dataSystem";
import { pullGetList } from "@/api/pull";
import 'vue3-cron-plus-picker/style.css'
import { Vue3CronPlusPicker } from 'vue3-cron-plus-picker'
import { getToken } from "@/utils/auth";
import axios from "axios";
import  * as XLSX from 'xlsx';

const { proxy } = getCurrentInstance();
const menuList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
const total = ref(0);

const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      keyword: null,
      systemId: null,
      enabled: null
   },
   detail: {},
   rules: {
      systemId: [{ required: true, message: "请选择所属系统", trigger: "change" }],
      name: [{ required: true, message: "请输入表名", trigger: "change" }],
      comment: [{ required: true, message: "请输入名称", trigger: "change" }],
      columnCategory: [{ required: true, message: "请选择字段类型", trigger: "change" }],
      columnName: [{ required: true, message: "请输入字段", trigger: "change" }],
      columnLength: [{ required: true, message: "请输入数据长度", trigger: "blur" }],
      columnType: [{ required: true, message: "请选择数据类型", trigger: "change" }],
   }
});

const { queryParams, form, detail, rules } = toRefs(data);
/** 查询系统列表 */
function getList() {
   loading.value = true;
   objectModelGetListByPage(queryParams.value).then(response => {
      menuList.value = response.data.records;
      total.value = response.data.total;
      loading.value = false;
   }).catch(()=>{
      proxy.$modal.msgError("获取列表数据失败");
      loading.value = false;
   });
}

const dataSystemOptions = ref([]);
/** 获取系统选项 */
function getDataSystemOption() {
   dataSystemGetList().then(response => {
      dataSystemOptions.value = response.data;
   });
}

function getSystemNameById(id) {
   return dataSystemOptions.value.find(item => item.id === id)?.name || '-'
}

const pullOptions = ref([]);
/** 获取任务选项 */
function getPullOption(systemId) {
   pullOptions.value = [];
   pullGetList({ systemId }).then(response => {
      pullOptions.value = response.data;
   });
}

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

/** 表单重置 */
function reset() {
   form.value = {
      systemId: null,
      name: null,
      comment: null,
      columns: [
         {
            comment: null,
            type: null,
            category: null,
            len: null,
            name: null
         }
      ]
   };
   detail.value = {};
   editTargetId.value = null;
   proxy.resetForm("editRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
   queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      keyword: null,
      systemId: null,
      enabled: null
   }
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   getDataSystemOption()
   title.value = "新增物模型";
}

const editTargetId = ref(null)
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   editTargetId.value = row.id
   const detail = JSON.parse(JSON.stringify(row))
   detail.columns.forEach(e => {
      // 从字符串中截取括号字符中间的文本内容
      const regex = /\(([^)]+)\)/;
      const match = regex.exec(e.type);
      e.len = match ? match[1] : null
      e.type = e.type?.replace(/\(.*\)/, '')
   });
   form.value = detail;
   open.value = true;
   title.value = "修改物模型";
   getDataSystemOption()
}
// 启用禁用
async function handleEnable(id, enable) {
   objectModelEnable({id, enable}).then(response => {
      getList();
   });
}

// 表名输入限制
function nameInput(){
   // 替换掉字母和下划线之外的文本
   form.value.name = form.value.name.replace(/[^a-zA-Z\_]/g, '')
}

// 操作数据拉取配置
function toggleConfig(type, index){
   if(type == 'minus'){
      form.value.columns.splice(index, 1)
      proxy.$refs["editRef"].validate()
   }else if(type == 'add'){
      form.value.columns.push({
         comment: null,
         type: null,
         category: null,
         len: null,
         name: null
      })
   }
}

const uploading = ref(false);
const fileUpload = ref(null)
const importFile = async (file) => {
   fileUpload.value.clearFiles()
   uploading.value = true;
   const formData = new FormData();
   formData.append("file", file.raw);
   const res = await axios.post(import.meta.env.VITE_APP_BASE_API + "/dynamic/table/excel/parse", formData, {
      headers: {
         "Content-Type": "multipart/form-data",
         Authorization: "Bearer " + getToken()
      },
   });

   if (res.data.code === 200) {
      proxy.$modal.msgSuccess('导入成功');
      const newArr = res.data.data.map(e => {
         // 从字符串中截取括号字符中间的文本内容
         const regex = /\(([^)]+)\)/;
         const match = regex.exec(e.type);
         return {
            name: e.name,
            category: e.category,
            comment: e.comment,
            len: match[1],
            type: e.type.replace(/\(.*\)/, '')
         }
      });
      form.value.columns = [ ...form.value.columns, ...newArr ]
   } else {
      proxy.$modal.msgError(res.data.msg);
   }
   uploading.value = false;
};

// 下载导入模板
const downloadTemplate = () => {
   const data = [
      ['字段类型', '字段名', '数据类型', '字段描述'],
      [1, '字段名', 'varchar(1)', '普通类型-字符串(长度1)'],
      [2, '字段名', 'int(2)', '字典类型-数字(长度2)'],
      [2, '字段名', 'blob(3)', '字典类型-文件流(长度3)'],
   ]
   const ws = XLSX.utils.aoa_to_sheet(data);
   const wb = XLSX.utils.book_new();
   XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
   XLSX.writeFile(wb, '物模型导入示例.xlsx');
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["editRef"].validate(valid => {
      if (valid) {
         const data = {
            // systemId: form.value.systemId,
            name: form.value.name,
            comment: form.value.comment,
            columns: form.value.columns.map(item => {
               return {
                  id:item.id,
                  name: item.name,
                  comment: item.comment,
                  category: item.category,
                  type: `${item.type}${ item.len !== null ? `(${item.len})` : ''}`
               }
            })
         }
         if (editTargetId.value) {
            objectModelUpdate({...data, id: editTargetId.value}).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               editTargetId.value = null;
               getList();
            });
         } else {
            objectModelAdd(data).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}

/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
      return objectModelDelete({ ids: row.id });
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

const selectedList = ref([])
function handleSelectionChange(list) {
   selectedList.value = list
}

/** 多选删除操作 */
function handleDeleteBatch() {
   if (selectedList.value.length) {
      proxy.$modal.confirm('是否确认删除选中的' + selectedList.value.length + '个数据?').then(function () {
         const ids = selectedList.value.map(item => item.id).join(',');
         return objectModelDelete({ ids });
      }).then(() => {
         getList();
         proxy.$modal.msgSuccess("删除成功");
      }).catch(() => { });
   } else {
      proxy.$modal.msgError("请选择要删除的数据");
   }
}

getList();
getDataSystemOption();
</script>
<style lang='scss' scoped>
.list{
   max-height: 500px;
   overflow-y: auto;
   overflow-x: hidden;
}
:deep(.el-row.edit-list){
   .el-col{
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
   }
   .el-form-item{
      width: 100%;
   }
}
</style>
